var SysConfig = (function () {
    var constants = {
        origin: "domain.com",
        loginUrl: "/login.html",
        indexUrl: "/index.html",
        apiUrl: "/"   //"http://localhost:11413/api/" //"http://"+document.domain+"/" 
    }
    var config = {};
    config.C = function (name) {
        return constants[name];
    }
    config.BaseUrl = function () {
        return "http://" + constants["origin"];
    }
    config.LoginUrl = function () {
        return config.BaseUrl() + constants["loginUrl"];
    }
    config.IndexUrl = function () {
        return config.BaseUrl() + constants["indexUrl"];
    }
    return config;
})();

var index;

var common = {

    getApi: function (url) {
        return SysConfig.C('apiUrl') + url;
    },

    invokeApi: function (method, url, postData, beforeSend, success, error, complete) {
        common.alert('url: ' + url);
        if (beforeSend === null || beforeSend === undefined)
            beforeSend = function (xhr) { };
        if (success === null || success === undefined)
            success = function (data) { };
        if (error === null || error === undefined)
            error = function (err) { };
        if (complete === null || complete === undefined)
            complete = function (err) { };
      
        var ajax_setting = {
            url: url,//this.getApi(url),
            type: method,
            dataType: "json",
            beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', 'BasicAuth ' + getCookie("auth"));
                common.alert('beforeSend');
                //common.loading();
                beforeSend();
            },
            success: function (data) { 
                common.alert('success data: ' + data);
                if (dealWithAjaxData(url, data)) {
                    success(data);
                } else {
                    error(data);
                }
            },
            error: function (data) {
                common.alert('error data: ' + data);
            },
            complete: function () {
                common.alert('complete');
                complete();
               // common.clearLoading();
            }
        };
        if (postData !== null && postData !== undefined) {          
            ajax_setting.data = JSON.stringify(postData);
            if (method == 'PUT' || method == 'POST') {
                ajax_setting.contentType = "application/json; charset=UTF-8";
            }
        }
        $.ajax(ajax_setting);
    },

    initAcTable: function (id,toolbar, method, url, successFn, errorFn, striped, pagination, search, pageSize, pageNumber, pageList, param) {
       
        common.loading();
    
        if (successFn === null || successFn === undefined)
            successFn = function (response) { };
        if (errorFn === null || errorFn === undefined)
            errorFn = function (e) { };
        if (pageList == null)
            pageList = [10, 20, 50,100];


        var obj = $('#'+id);
        obj.bootstrapTable('destroy');

        var pl = pageList.toString().split(",");
        var setting = {
            method: method,
            toolbar: '#' + toolbar,
            url: url,//common.getApi(url),
            striped: striped,
            pagination: pagination,
            pageSize: pageSize,
            pageNumber: pageNumber,
            pageList: pageList,
            sortable: true,  
            sortOrder: "desc",  
            search: search,
            sidePagination: "server",
            queryParamsType: "limit",
            contentType: "application/x-www-form-urlencoded",
            queryParams: function queryParams(params) {
                param.limit = params.limit;
                param.offset = params.offset;
                param.sortName = params.sort;
                param.sortOrder = params.order;
                param.Authorization = getCookie("Authorization");
                return param;
            },
            onLoadSuccess: function (data) {
                successFn(data);
            },
            onLoadError: function (e) {
                errorFn(e);
                common.tips("加载数据失败", 2);
            },
            responseHandler: function (response) {
                if (!response.State) {
                    common.msg(res.Message, 2);
                }
                return {
                    State: response.State,
                    Message: response.Message,
                    total: response.Datas.Total,
                    rows: response.Datas.Rows
                };
            },
        };

       

        obj.bootstrapTable(setting);
        common.clearLoading();
    },
     
    checkLoginStatus: function () { //检查登录状态
        if (!getCookie("Authorization"))
        {
            common.toLogin();
        }
    },

    toLogin: function () {
        delCookie("Authorization");
        window.location.href = "/login.html";
    },

    ready: function (fn) { //先确保登录完成，再做其他操作
        $.when(login_dtd).done(fn);
    },

    _GET: function () {
        var u = location.search;
        var get = {};
        if (u === '' || u === undefined) {
            return get;
        } else {
            u = u.substr(1).split('&');
        }

        for (var i in u) {
            var j = u[i].split("=");
            get[j[0]] = j[1];
        }
        // 特殊处理，如果是是微信分享的链接，把code参数去掉
        if (get.from) { //分享带from参数
            delete get.code;
        }
        return get;
    },

    log: function () {
        var len = arguments.length;
        for (var i = 0; i < len; i++) {
            console.log(arguments[i]);
        }
    },

    alert: function (data) {
        console.log(data);
    },

    loading: function () { 
        index = layer.load(1, {
            shade: [0.9, '#aaa']  
        });
    },

    clearLoading: function () {
        if (index) {
            layer.close(index);
        }
    },

    msg: function (msg, icon,fn) {
        icon = icon ? icon : 0;
        layer.msg(msg, {
            icon: icon,
            skin: 'layer-ext-moon',
            shade: [0.9, '#aaa'],
            time:800
        }, function () {
            if(typeof(fn)=="function")
            fn();
        });
    },

    tips: function (msg, obj,type) {
        layer.tips(msg, obj, {
            tips: [type, '#78BA32']
        })
    },
    
    setTitle: function (title) {
        $('title').text(title);
    },

    errorProcess: function (data) {
        var type = data.type;
        switch (data.type) {
            case 'refresh':
                doRefresh();
                break;
            case 'alert':
                doAlert(data.text);
                break;
            case 'redirect':
                doRedirect(data.text, data.url);
                break;
            default:
                break;
        }
    },

    removeParamFromUrl: function (paramArray) {
        var urlParam = common._GET();
        common.log(urlParam);
        for (var i in paramArray) {
            delete urlParam[paramArray[i]]; //删除code属性
        }
        return location.pathname + common.buildUrlParamString(urlParam);
    },

    buildUrlParamString: function (urlParam) {
        var strUrlParam = "";
        for (var key in urlParam) {
            strUrlParam += key + '=' + urlParam[key] + '&';
        }
        strUrlParam = strUrlParam.slice(0, strUrlParam.length - 1);
        var flag = (strUrlParam === '' || strUrlParam === undefined);
        return flag ? '' : '?' + strUrlParam;
    }
};

function dealWithAjaxData(url, data) {
    common.log(url, data);
    if (data.State) {
        return true;
    }
    common.alert('error_code: ' + data.Message)
    return false;
}

function doRedirect(text, url) {
    var winpop = new Winpop();
    winpop.alert(text)
    $.when(winpop.self._d_pop).done(function () {
        switch (url) {
            case 'back':
                window.history.back();
                break;
            case 'reload':
                location.reload();
                break;
            default:
                location.href = url;
                break;
        }
    })

}

function getCookie(c_name) {
    return $.cookie(c_name);
}

function setCookie(name, value, expires) {
    $.cookie(name, value, new Date(expires * 1000));   
}

function delCookie(c_name) {
    $.cookie(c_name, null, { expires: -1, path: '/' });
}

function getWeishopAccessToken() {
    return getCookie('AccessToken');
}

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function decimalFormatter(value, row, index) {
    return "￥ " + value.toFixed(2);
}

function dateFormatter(value, row, index) {
    var birthdayMilliseconds = parseInt(value.replace(/\/Date\(/igm, ""));
    return new Date(birthdayMilliseconds).Format("yyyy-MM-dd hh:mm:ss"); 
}